package com.chen.nongansampling.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chen.nongansampling.MainActivity;
import com.chen.nongansampling.R;
import com.chen.nongansampling.adapter.SampledRecycleViewAdapter;
import com.chen.nongansampling.app.BaseApplication;
import com.chen.nongansampling.bean.SampledListBean;
import com.chen.nongansampling.bean.request.GetSampledRequest;
import com.chen.nongansampling.fragment.ui.sample.SampleFragment;
import com.chen.nongansampling.model.CallbackData;
import com.chen.nongansampling.presenter.SampledPresenter;
import com.chen.nongansampling.presenterView.SampledView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SampledFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SampledFragment extends androidx.fragment.app.Fragment implements SampledView {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    //    @BindView(R.id.search)
//    Button search;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.search_view)
    SearchView searchView;

    private SampledPresenter sampledPresenter = new SampledPresenter(getContext());
   private  SampledRecycleViewAdapter sampledRecycleViewAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public SampledFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SampledFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SampledFragment newInstance(String param1, String param2) {
        SampledFragment fragment = new SampledFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public static SampledFragment newInstance() {
        return new SampledFragment();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        sampledPresenter.onCreate();
        sampledPresenter.BindPresentView(this);


    }


    public void onCreateMenu() {


//        menu.clear();
//   //     inflater.inflate(R.menu.main_menu_item, menu);
//        inflater.inflate(R.menu.notes, menu);
//
//        //通过反射让menu的图标可见
//        if (menu != null) {
//            if (menu.getClass() == MenuBuilder.class) {
//                try {
//                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
//                    m.setAccessible(true);
//                    m.invoke(menu, true);
//                } catch (Exception e) {
//
//                }
//            }
//        }
//
//        //这一行不能忘，否则看不到图标
//        //拿到ActionBar后，可以进行设置
//        ((AppCompatActivity) getActivity()).getSupportActionBar();
//        super.onCreateOptionsMenu(menu, inflater);


        Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
//        getActivity().setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);//隐藏标题
        toolbar.setNavigationIcon(R.mipmap.back_white);       //加载图标
        toolbar.setTitle("");
        //toolbar.setOverflowIcon(ContextCompat.getDrawable(getContext(),R.mipmap.add_sample));

        ImageButton imageButton = getActivity().findViewById(R.id.add_sample);
        imageButton.setVisibility(View.VISIBLE);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("2333", "qqqq");
                getActivity().getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, SampleFragment.newInstance(),"wxsSampleFragment")
//                .addToBackStack("SampleFragment")
                        .commitNow();

            }
        });
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {   //为图标设置监听器
            @Override
            public void onClick(View v) {

                Intent intent= new Intent();
                intent.setClass(getActivity(), MainActivity.class);

                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(intent);
            }
        });

        toolbar.setNavigationIcon(R.mipmap.back_white);       //加载图标


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment


        View view = inflater.inflate(R.layout.fragment_sampled, container, false);
        ButterKnife.bind(this, view);


        //return inflater.inflate(R.layout.fragment_sampled, container, false);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
//    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onCreateMenu();

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());

        recyclerView.setLayoutManager(layoutManager);
        //默认就是垂直方向的
        ((LinearLayoutManager) layoutManager).setOrientation(RecyclerView.VERTICAL);


        GetSampledRequest getSampledRequest = new GetSampledRequest();
        getSampledRequest.setAccountPkId(BaseApplication.getAccount().getPkId());
        getSampledRequest.setIndexStr("");
        //System.out.println("getSampledRequestgetSampledRequestgetSampledRequestgetSampledRequestgetSampledRequestgetSampledRequestgetSampledRequest"+getSampledRequest.toString());
        sampledPresenter.getSampledListResponseInfo(getSampledRequest);



//        searchView.setOnSearchClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                recyclerView.setAdapter(null);
//                GetSampledRequest getSampledRequest = new GetSampledRequest();
//                getSampledRequest.setAccountPkId(BaseApplication.getAccount().getPkId());
//                getSampledRequest.setIndexStr(searchView.getQuery().toString());
//                sampledPresenter.getSampledListResponseInfo(getSampledRequest);
//
//                Log.d("sampled666", searchView.getQuery().toString());
//
//            }
//        }
//        );
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                      //          recyclerView.setAdapter(null);
                      //          recyclerView.
                GetSampledRequest getSampledRequest = new GetSampledRequest();
                getSampledRequest.setAccountPkId(BaseApplication.getAccount().getPkId());
                getSampledRequest.setIndexStr(query);

                sampledPresenter.getSampledListResponseInfo(getSampledRequest);
                Log.d("sampled66666666666666", searchView.getQuery().toString());
                //Toast.makeText(getActivity(),getSampledRequest.toString(),Toast.LENGTH_LONG).show();

                Log.d("sampled666", getSampledRequest.toString());

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.equals(""))
                {
                    GetSampledRequest getSampledRequest = new GetSampledRequest();
                    getSampledRequest.setAccountPkId(BaseApplication.getAccount().getPkId());
                    getSampledRequest.setIndexStr("");
                    sampledPresenter.getSampledListResponseInfo(getSampledRequest);
                    Log.d("sampled111", getSampledRequest.toString());

                    //Toast.makeText(getActivity(),getSampledRequest.toString(),Toast.LENGTH_LONG).show();

                }
                return false;
            }
        });



    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    @Override
    public void onError(String result) {
        Log.d("sampledError", result);
    }

    @Override
    public void onSuccess(Object resultData) {

    }

    @Override
    public void getSampledList(Object resultData) {


        CallbackData<List<SampledListBean>> listCallbackData = (CallbackData<List<SampledListBean>>) resultData;

        Log.d("sampled", listCallbackData.getData().toString());

        sampledRecycleViewAdapter=new SampledRecycleViewAdapter(getActivity(), listCallbackData.getData(),this);
        recyclerView.setAdapter(sampledRecycleViewAdapter);
        sampledRecycleViewAdapter.notifyDataSetChanged();
        sampledRecycleViewAdapter.setRecyclerView(recyclerView);


//        recyclerView.notifyAll();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


}
